// 设置页面功能

// 重置所有Cookie
function resetCookies() {
    const douyinCookies = document.getElementById('douyinCookies');
    const kuaishouCookies = document.getElementById('kuaishouCookies');
    
    if (douyinCookies) douyinCookies.value = '';
    if (kuaishouCookies) kuaishouCookies.value = '';
    
    showToast('✅ 抖音和快手Cookie已重置', 'success');
}

// 重置设置为默认值
function resetSettings() {
    const defaultPath = document.getElementById('defaultPath');
    const downloadThreads = document.getElementById('downloadThreads');
    const timeout = document.getElementById('timeout');
    
    if (defaultPath) defaultPath.value = 'D:/douyin_downloads';
    if (downloadThreads) downloadThreads.value = '3';
    if (timeout) timeout.value = '30';
    
    showToast('✅ 设置已恢复为默认值', 'success');
}

// 应用代理设置
function applyProxySettings() {
    const proxyEnabled = document.getElementById('proxyEnabled').checked;
    const proxyType = document.getElementById('proxyType').value;
    const proxyHost = document.getElementById('proxyHost').value;
    const proxyPort = document.getElementById('proxyPort').value;
    const proxyAuthEnabled = document.getElementById('proxyAuthEnabled').checked;
    const proxyUsername = document.getElementById('proxyUsername').value;
    const proxyPassword = document.getElementById('proxyPassword').value;
    
    // 验证代理设置
    if (proxyEnabled) {
        if (!proxyHost || !proxyPort) {
            showToast('❌ 请填写代理地址和端口', 'error');
            return;
        }
        
        if (proxyAuthEnabled && (!proxyUsername || !proxyPassword)) {
            showToast('❌ 请填写代理认证用户名和密码', 'error');
            return;
        }
    }
    
    // 发送代理设置到后端
    const message = {
        'type': 'apply_proxy_settings',
        'proxy_enabled': proxyEnabled,
        'proxy_type': proxyType,
        'proxy_host': proxyHost,
        'proxy_port': proxyPort,
        'proxy_auth_enabled': proxyAuthEnabled,
        'proxy_username': proxyUsername,
        'proxy_password': proxyPassword
    };
    
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify(message));
        showToast('✅ 代理设置已应用', 'success');
    } else {
        showToast('❌ WebSocket连接已断开，无法应用设置', 'error');
    }
}

// 测试代理连接
function testProxyConnection() {
    const proxyEnabled = document.getElementById('proxyEnabled').checked;
    const proxyType = document.getElementById('proxyType').value;
    const proxyHost = document.getElementById('proxyHost').value;
    const proxyPort = document.getElementById('proxyPort').value;
    const proxyAuthEnabled = document.getElementById('proxyAuthEnabled').checked;
    const proxyUsername = document.getElementById('proxyUsername').value;
    const proxyPassword = document.getElementById('proxyPassword').value;
    
    // 验证代理设置
    if (!proxyEnabled) {
        showToast('❌ 请先启用代理', 'error');
        return;
    }
    
    if (!proxyHost || !proxyPort) {
        showToast('❌ 请填写代理地址和端口', 'error');
        return;
    }
    
    if (proxyAuthEnabled && (!proxyUsername || !proxyPassword)) {
        showToast('❌ 请填写代理认证用户名和密码', 'error');
        return;
    }
    
    // 发送测试请求到后端
    const message = {
        'type': 'test_proxy_connection',
        'proxy_type': proxyType,
        'proxy_host': proxyHost,
        'proxy_port': proxyPort,
        'proxy_auth_enabled': proxyAuthEnabled,
        'proxy_username': proxyUsername,
        'proxy_password': proxyPassword
    };
    
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify(message));
        showToast('⏳ 正在测试代理连接...', 'info');
    } else {
        showToast('❌ WebSocket连接已断开，无法测试代理', 'error');
    }
}

// 应用Cookie设置（保留旧版本兼容性）
function applyCookies() {
    const douyinCookies = document.getElementById('douyinCookies')?.value.trim() || '';
    const kuaishouCookies = document.getElementById('kuaishouCookies')?.value.trim() || '';

    if (!douyinCookies && !kuaishouCookies) {
        showToast('❌ 请至少填写一个平台的Cookie', 'error');
        return;
    }

    // 发送Cookie设置到后端
    const message = {
        'type': 'apply_cookies',
        'douyin_cookies': douyinCookies,
        'kuaishou_cookies': kuaishouCookies,
        'vmq_cookies': 'default_internal_cookie', // 使用内置Cookie
        'tiefenquan_cookies': 'default_internal_cookie' // 使用内置Cookie
    };

    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify(message));
        showToast('✅ Cookie设置已应用', 'success');
    } else {
        showToast('❌ WebSocket连接已断开，无法应用设置', 'error');
    }
}

// ============================================
//   🍪 新版Cookie管理功能
// ============================================

// 更新指定平台的Cookie
async function updatePlatformCookies(platform) {
    const inputId = `${platform}CookieInput`;
    const cookieInput = document.getElementById(inputId);

    if (!cookieInput) {
        showToast(`❌ 找不到${platform}Cookie输入框`, 'error');
        return;
    }

    const cookies = cookieInput.value.trim();

    if (!cookies) {
        showToast(`❌ 请输入${platform}的Cookie数据`, 'error');
        return;
    }

    try {
        const response = await fetch('/api/cookies/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                cookies: cookies,
                platform: platform
            })
        });

        const result = await response.json();

        if (response.ok) {
            showToast(`✅ ${getPlatformName(platform)}Cookie更新成功`, 'success');
            // 保存到本地存储
            localStorage.setItem(`${platform}_cookies`, cookies);
        } else {
            showToast(`❌ ${getPlatformName(platform)}Cookie更新失败: ${result.detail}`, 'error');
        }
    } catch (error) {
        showToast(`❌ ${getPlatformName(platform)}Cookie更新失败: ${error.message}`, 'error');
    }
}

// 清空指定平台的Cookie
async function clearPlatformCookies(platform) {
    const inputId = `${platform}CookieInput`;
    const cookieInput = document.getElementById(inputId);

    if (!cookieInput) {
        showToast(`❌ 找不到${platform}Cookie输入框`, 'error');
        return;
    }

    // 清空输入框
    cookieInput.value = '';

    try {
        const response = await fetch('/api/cookies/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                cookies: '',
                platform: platform
            })
        });

        const result = await response.json();

        if (response.ok) {
            showToast(`✅ ${getPlatformName(platform)}Cookie已清空`, 'success');
            // 清除本地存储
            localStorage.removeItem(`${platform}_cookies`);
        } else {
            showToast(`❌ ${getPlatformName(platform)}Cookie清空失败: ${result.detail}`, 'error');
        }
    } catch (error) {
        showToast(`❌ ${getPlatformName(platform)}Cookie清空失败: ${error.message}`, 'error');
    }
}

// 获取平台中文名称
function getPlatformName(platform) {
    const platformNames = {
        'douyin': '抖音',
        'kuaishou': '快手',
        'bilibili': 'B站'
    };
    return platformNames[platform] || platform;
}

// 页面加载时从本地存储恢复Cookie
function loadSavedCookies() {
    const platforms = ['douyin', 'kuaishou', 'bilibili'];

    platforms.forEach(platform => {
        const savedCookies = localStorage.getItem(`${platform}_cookies`);
        if (savedCookies) {
            const inputId = `${platform}CookieInput`;
            const cookieInput = document.getElementById(inputId);
            if (cookieInput) {
                cookieInput.value = savedCookies;
            }
        }
    });
}

// 应用通用设置
function applySettings() {
    const defaultPath = document.getElementById('defaultPath').value.trim();
    const downloadThreads = document.getElementById('downloadThreads').value;
    const timeout = document.getElementById('timeout').value;
    
    if (!defaultPath) {
        showToast('❌ 请设置默认下载路径', 'error');
        return;
    }
    
    // 发送通用设置到后端
    const message = {
        'type': 'apply_general_settings',
        'default_path': defaultPath,
        'download_threads': parseInt(downloadThreads),
        'timeout': parseInt(timeout)
    };
    
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify(message));
        showToast('✅ 通用设置已应用', 'success');
    } else {
        showToast('❌ WebSocket连接已断开，无法应用设置', 'error');
    }
}

// 密码修改功能
async function changePasswordSettings() {
    const currentPassword = document.getElementById('currentPassword').value.trim();
    const newPassword = document.getElementById('newPassword').value.trim();
    const confirmPassword = document.getElementById('confirmPassword').value.trim();
    const statusDiv = document.getElementById('passwordStatus');
    const statusText = document.getElementById('passwordStatusText');
    
    // 隐藏之前的状态
    statusDiv.style.display = 'none';
    
    // 验证输入
    if (!currentPassword) {
        showPasswordStatus('请输入当前密码', 'error');
        return;
    }
    
    if (!newPassword) {
        showPasswordStatus('请输入新密码', 'error');
        return;
    }
    
    if (newPassword.length < 4) {
        showPasswordStatus('新密码长度至少为4位', 'error');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        showPasswordStatus('两次输入的新密码不一致', 'error');
        return;
    }
    
    if (currentPassword === newPassword) {
        showPasswordStatus('新密码不能与当前密码相同', 'error');
        return;
    }
    
    try {
        // 发送密码修改请求
        const response = await fetch('/api/password/change', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                current_password: currentPassword,
                new_password: newPassword,
                client_id: clientId || 'web_client'
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showPasswordStatus('✅ 密码修改成功！', 'success');
            showToast('🔒 密码修改成功！', 'success');
            // 清空输入框
            resetPasswordFields();
        } else {
            showPasswordStatus(`❌ ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('密码修改请求失败:', error);
        showPasswordStatus('❌ 网络请求失败，请检查连接', 'error');
    }
}

// 重置密码输入框
function resetPasswordFields() {
    document.getElementById('currentPassword').value = '';
    document.getElementById('newPassword').value = '';
    document.getElementById('confirmPassword').value = '';
    document.getElementById('passwordStatus').style.display = 'none';
}

// 显示密码状态
function showPasswordStatus(message, type) {
    const statusDiv = document.getElementById('passwordStatus');
    const statusText = document.getElementById('passwordStatusText');
    
    statusText.textContent = message;
    
    // 设置样式
    statusDiv.style.display = 'block';
    statusDiv.style.backgroundColor = type === 'success' ? 'rgba(76, 175, 80, 0.2)' : 'rgba(244, 67, 54, 0.2)';
    statusDiv.style.border = type === 'success' ? '1px solid rgba(76, 175, 80, 0.5)' : '1px solid rgba(244, 67, 54, 0.5)';
    statusText.style.color = type === 'success' ? '#4CAF50' : '#F44336';
    
    // 3秒后自动隐藏
    setTimeout(() => {
        statusDiv.style.display = 'none';
    }, 3000);
}

// 确保所有函数在全局作用域中可用
window.changePasswordSettings = changePasswordSettings;
window.resetPasswordFields = resetPasswordFields;
window.showPasswordStatus = showPasswordStatus;
